import type { IFile } from './Files'
import { ISendReq } from './interface'

export const fileMax = 5
export const filesMax = 10
export const fileSizeTip = `单个附件大小不能超过${fileMax}MB`
export const filesSizeTip = `附件总大小不能超过${filesMax}MB`

export const fileToBase64 = async (files: IFile[]): Promise<ISendReq['attachments']> => {
  return Promise.all(
    files.map(d => {
      return new Promise<ISendReq['attachments'][number]>((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = event => {
          const base64String = (event.target?.result || '') as string
          resolve({
            name: d.fileName,
            content: base64String.split(',')[1],
            contentType: d.file.type,
          })
        }
        reader.onerror = () => reject()
        reader.readAsDataURL(d.file)
      }).catch(err => {
        console.error(err)
        throw new Error('读取文件时出错')
      })
    }),
  )
}
